import { useReducer } from "react";

// 纯函数
/*
  1. 不能执行带副作用的调用（包括：ajax, 打开数据库，console.log）
  2. 返回值里不能有类似Math.random()/Date.now()
  3. 它不能改变参数或环境里的变量值
*/
const reducer = (state, action) => { // 纯函数
  switch(action.type) {
    case 'incr':
      return {count: state.count+1} // nextState
    case 'decr':
      return {count: state.count-1} // nextState
    case 'incrAmount':
      return {count: state.count + action.amout} // nextState
    default:
      return state
  }
}

const ReducerDemo = () => {
  const [state, dispatch] = useReducer(reducer, {count: 0})
  return ( <>
      <h2>useReducer例子</h2>
      计数器：{state.count}
      <button onClick={() => dispatch({type: 'incr'})}>
        incr</button>
      <button onClick={() => dispatch({type: 'decr'})}>
      decr</button>
      <button onClick={() => dispatch({type: 'incrAmount', amout: 2})}>
      incr 2</button>
    </> );
}

export default ReducerDemo;